package com.dhecp.project.hr.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.core.utils.ReadExcel;
import com.dhecp.core.vo.W;
import com.dhecp.framework.web.service.BaseInfoSimpleService;
import com.dhecp.project.api.util.ApiConfig;
import com.dhecp.project.base.domain.BaseInfo;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.hr.domain.AmazonRegion;
import com.dhecp.project.hr.domain.AmazonRegionItem;
import com.dhecp.project.hr.domain.AmazonShop;
import com.dhecp.project.hr.domain.OperateCompanyApply;
import com.dhecp.project.hr.service.AmazonRegionItemService;
import com.dhecp.project.hr.service.AmazonRegionService;
import com.dhecp.project.hr.service.AmazonShopService;
import com.dhecp.project.hr.service.OperateCompanyApplyService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @program: kjecp
 * @description: 网店资料绑定 控制层
 * @author: hlf
 * @create: 2022-10-09 10:14
 */
@Controller
@RequestMapping("/hr/amazonshop")
public class AmazonShopController extends BaseModuleController {

    private String prefix = "hr/amazonshop";
    private String moduleTable = ModuleTable.AMAZON_SHOP;

    @Autowired
    private AmazonShopService businessService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;


    @Autowired
    private AmazonRegionService amazonRegionService;
    @Autowired
    private AmazonRegionItemService amazonRegionItemService;
    @Autowired
    private BaseInfoSimpleService baseInfoSimpleService;
    @Autowired
    private OperateCompanyApplyService operateCompanyApplyService;

    /**
     * 打开查询列表页
     * @param params
     * @return
     * @author DH-Xxj 
     */
    @RequiresPermissions("hr:amazonshop:view")
    @GetMapping()
    public ModelAndView listPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new AmazonShop()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix",prefix + "/amazonshop"); //页面路径
        params.put("checkBox", "yes");
        params.put("toolBarWidth", 300);
        ModelAndView mv = this.openListPage(params);
        mv.addObject("hr", "amazonshop");
        mv.addObject("ali1688AppKey", ApiConfig.getAli1688AppKey());
        mv.addObject("ali1688EcpApiUrl", ApiConfig.getAli1688EcpApiUrl());
        return mv;
    }

    /**
     * 打开制单页
     * @param nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("hr:amazonshop:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new AmazonShop()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
        List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
        List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        AmazonShop infoItem = new AmazonShop();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            infoItem = businessService.findByGuid(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
            params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
            dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            if (dicFieldsList.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                for (SysDictionaryForPageField dicFields : dicFieldsList){
                    Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);

                    if (infoItem!=null){
                        Map<String, Object> infoData = TypeUtils.entityToMap(infoItem);
                        fieldsListMap.put("fieldContent", infoData.get(fieldsListMap.get("fields")));
                    }else{
                        fieldsListMap.put("fieldContent", "");

                    }
                    if (fieldsListMap.get("fieldFrontType") == null){
                        fieldsListMap.put("fieldFrontType", "t_text");
                    }

                    //如果有下拉控件，则根据配置获取对应下拉待选内容
                    List<BaseInfo> dropdownList = new ArrayList<BaseInfo>();
                    String fieldFrontType = dicFields.getFieldFrontType();
                    String fieldSearchType = dicFields.getFieldSearchType();
                    String fieldFrontSave = dicFields.getFieldFrontSave();
                    String fieldFrontShow = dicFields.getFieldFrontShow();
                    if (fieldFrontType != null && fieldFrontType.toLowerCase().startsWith("t_dropdown")){
                        if (fieldSearchType != null && !"".equals(fieldSearchType)){
                            if (fieldFrontSave == null || "".equals(fieldFrontSave)){
                                fieldFrontSave = "vid";
                            }
                            if (fieldFrontShow == null || "".equals(fieldFrontShow)){
                                fieldFrontShow = "vname";
                            }
                            dropdownList = baseInfoSimpleService.getDropdownData(fieldSearchType,fieldFrontSave,fieldFrontShow);
                        }
                    }
                    fieldsListMap.put("dropdownList", dropdownList);

                    if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
                        fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                    }else {	//隐藏的字段
                        fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                    }
                }
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap)); //各字段及属性
        mv.addObject("fieldsList", fieldsList);				//显示的字段
        mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
        mv.addObject("amazonShop", infoItem);	//字段
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/amazonshop_edit");
        return mv;

    }

    /**
     * 打开重启VPS实例
     * @author XDH
     */
//    @RequiresPermissions("hr:amazonshop:view")
    @GetMapping("/toRerverRestart")
    public ModelAndView toRerverRestart(@RequestParam Map<String, Object> params) throws Exception{
        ModelAndView mv = this.getModelAndView();

        params.put("moduleTable", moduleTable);
        params.put("entity", new AmazonShop());
        if (!params.containsKey("guid")) {
			return W.error(mv, "ID不能为空");
		}
        String guid = params.get("guid").toString();
        if (guid == null || guid.length() == 0) {
			return W.error(mv, "ID不能为空");
		}
        
        AmazonShop entity = businessService.findByGuid(params);
        if (entity == null) {
			return W.error(mv, "数据不存在");
		} else if (entity.getServerInstanceId() == null || entity.getServerInstanceId().length() == 0) {
			return W.error(mv, "尚未绑定实例ID");
		}
        
        String serverInstanceId = entity.getServerInstanceId();
        String serverIp = entity.getServerIp();
        String serverAws = entity.getServerAws();
        String url = "https://owfswpyrye.execute-api.cn-northwest-1.amazonaws.com.cn/prod";
        if (serverAws != null && serverAws.length() > 0 && "313192766079".equals(serverAws)) {
			url = "https://2g9jicyufb.execute-api.cn-northwest-1.amazonaws.com.cn/prod";
		}
        ToRerverRestartDto dto = new ToRerverRestartDto(serverInstanceId, serverIp, url);
        mv.addObject("dto", dto);
        mv.setViewName(prefix + "/toRerverRestart");
        return mv;
    }
	@Data
	@AllArgsConstructor
	private static class ToRerverRestartDto{
		private String serverInstanceId; // 实例ID
		private String serverIp; // 实例IP
		private String url; // 请求URL
	}

    /**
     * 打开VPS重启密码页
     * @author XDH
     */
//    @RequiresPermissions("hr:amazonshop:view")
    @GetMapping("/toResetPass")
    public ModelAndView toResetPass(@RequestParam Map<String, Object> params) throws Exception{
        ModelAndView mv = this.getModelAndView();

        params.put("moduleTable", moduleTable);
        params.put("entity", new AmazonShop());
        if (!params.containsKey("guid")) {
			return W.error(mv, "ID不能为空");
		}
        String guid = params.get("guid").toString();
        if (guid == null || guid.length() == 0) {
			return W.error(mv, "ID不能为空");
		}
        
        AmazonShop entity = businessService.findByGuid(params);
        if (entity == null) {
			return W.error(mv, "数据不存在");
		} else if (entity.getServerInstanceId() == null || entity.getServerInstanceId().length() == 0) {
			return W.error(mv, "尚未绑定实例ID");
		}
        
        String serverInstanceId = entity.getServerInstanceId();
        String serverIp = entity.getServerIp();
        ToResetPassDto dto = new ToResetPassDto(serverInstanceId, serverIp);
        mv.addObject("dto", dto);
        mv.setViewName(prefix + "/toResetPass");
        return mv;
    }
	@Data
	@AllArgsConstructor
	private static class ToResetPassDto{
		private String serverInstanceId; // 实例ID
		private String serverIp; // 实例IP
	}



    /**
     * 查询页 列表数据
     * @param params
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("hr:amazonshop:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        List<AmazonShop> list = new ArrayList<AmazonShop>();
        try {
            list = businessService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * 打开选择列表
     * @param
     * @return ModelAndView
     * @author DH-lwl
     */
    @GetMapping("/select")
    public ModelAndView selectList(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new AmazonShop()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);
        if(params.get("pagetype") !=null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))params.put("checkBox", "yes");
        else params.put("radio", "yes");
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();

        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("prefix", prefix);
        mv.addObject("moduleTable", moduleTable);
        mv.setViewName("common/select");
        return mv;
    }

    /**
     * 数据导出Excel
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @RequiresPermissions("hr:amazonshop:export")
    @Log(title = "网店资料绑定导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new AmazonShop());

        List<AmazonShop> list = businessService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<AmazonShop> util = new ExportExcelUtils<AmazonShop>(moduleTable,new AmazonShop());
        return util.exportExcel(list, fieldList, "网店资料绑定", "export");
    }

    /**
     * 导出Excel导入模板
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @RequiresPermissions("hr:amazonshop:import")
    @Log(title = "网店资料绑定导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exporttemplate")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult exportTemplate(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new AmazonShop());

        params.put("getFieldAttributesType", "template");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<AmazonShop> util = new ExportExcelUtils<AmazonShop>(moduleTable,new AmazonShop());
        return util.exportExcel(null, fieldList, "网店资料绑定导入模板", "template");
    }

    /**
     * 保存数据
     * @param infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @param infoItems 必要参数：对应实体类的json格式字符串
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions(value={"hr:amazonshop:add","hr:amazonshop:edit","hr:amazonshop:delete"},logical= Logical.OR)
    @Log(title = "网店资料绑定", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= businessService.saveData(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 保存数据
     * @param infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @param infoItems 必要参数：对应实体类的json格式字符串
     * @return
     * @author XDH
     */
    @GetMapping("/editpostLocal")
    @ResponseBody
    public AjaxResult editpostLocal(){
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            List<List<String>> rows = ReadExcel.getRowsByFile("d:\\Users\\Administrator\\Desktop\\导入ERP\\店铺信息.xlsx", 1);
            for (int i = 1; i < rows.size(); i++) {
            	List<String> row = rows.get(i);
            	
            	// 验证店铺名称
            	String shopName = row.get(1);
            	AmazonShop amazonShop = businessService.findByShopName(shopName);
            	if (amazonShop != null) {
            		continue;
				}
            	
            	String gsjc = row.get(8);
            	OperateCompanyApply operateCompanyApply = operateCompanyApplyService.findByShortName(gsjc);
            	if (operateCompanyApply == null) {
            		continue;
				}
            	
            	Map<String, Object> params = new HashMap<String, Object>();
            	
            	JSONObject JO = new JSONObject();
            	JO.put("vAT", "");
            	JO.put("eORI", "");
            	JO.put("districtOrCounty", "");
            	JO.put("name", "");
            	JO.put("addressLine1", "");
            	JO.put("addressLine2", "");
            	JO.put("city", "");
            	JO.put("stateOrProvinceCode", "");
            	JO.put("phone", "");
            	JO.put("postalCode", "");
            	JO.put("shopUser", row.get(0));
            	JO.put("shopName", shopName);
            	JO.put("sellerId", row.get(2));
            	
            	JO.put("companyID", operateCompanyApply.getvGsBm());
            	JO.put("companyName", operateCompanyApply.getvGsMc());
            	JO.put("companyName2", operateCompanyApply.getvGsJc());
            	
            	String regionName = row.get(3);
            	AmazonRegion amazonRegion = amazonRegionService.findByName(regionName);
            	if (amazonRegion == null) {
					continue;
				}
            	JO.put("areas", amazonRegion.getGuid());
            	JO.put("regionGuid", amazonRegion.getGuid());
            	JO.put("regionName", amazonRegion.getRegionName());
            	
            	JO.put("regionCountryCode", "");

            	String countryName = row.get(4);
            	AmazonRegionItem amazonRegionItem = amazonRegionItemService.findByName(countryName);
            	if (amazonRegionItem == null) {
					continue;
				}
            	JO.put("country", amazonRegionItem.getMarketplaceId());
            	JO.put("countryCode", amazonRegionItem.getCountryCode());
            	JO.put("countryName", countryName);
            	JO.put("guid", "");
            	JO.put("marketplaceIds", amazonRegionItem.getMarketplaceId());
            	JO.put("authorizeState", "");
            	JO.put("accessToken", "");
            	JO.put("refreshToken", "");
            	JO.put("expireDate", "");
            	JO.put("lastOrderSyncDate", "");
            	JO.put("originalShopUser", "");
            	params.put("infoItems", JO.toJSONString());
            	
            	
        		params.put("moduleTable", moduleTable);
        		
                System.out.println(JSON.toJSONString(params));
                ajaxResult= businessService.saveData(params);
            }
            
        }catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }



    /**
     * @Description: 删除未审核数据
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-08-17 14:55
     */
    @RequiresPermissions("hr:amazonshop:delete")
    @Log(title = "删除网店资料绑定", businessType = BusinessType.UPDATE)
    @PostMapping("/delete")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult delete(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = businessService.deleteData(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }




    /**
     * 获取区域数据
     * @param params
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("hr:amazonshop:list")
    @GetMapping("/getAmazonRegion")
    @ResponseBody
    public TableDataInfo getAmazonRegion(@RequestParam Map<String, Object> params){
        List<AmazonRegion> list = new ArrayList<AmazonRegion>();
        try {
            list = businessService.queryRegionList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }



    /**
     * 获取国家数据
     * @param params
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("hr:amazonshop:list")
    @GetMapping("/getAmazonRegionItem")
    @ResponseBody
    public TableDataInfo getAmazonRegionItem(@RequestParam Map<String, Object> params){
        List<AmazonRegionItem> list = new ArrayList<AmazonRegionItem>();
        try {
            list = businessService.queryRegionItemList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

}